import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:robotcontrol/entity/common_item.dart';
import 'package:robotcontrol/http/http_manager.dart';
import 'package:robotcontrol/http/url.dart';
import 'package:robotcontrol/page/video_page/video_play_widget.dart';
import 'package:robotcontrol/page/video_page/video_item_widget.dart';
import 'package:robotcontrol/utils/cache_image.dart';
import 'package:robotcontrol/utils/date_util.dart';
import 'package:robotcontrol/utils/navigator_util.dart';
import 'package:robotcontrol/utils/tip_util.dart';
import 'package:robotcontrol/utils/toast.dart';
import 'package:robotcontrol/widgets/loading_state_widget.dart';

const VIDEO_SMALL_CARD_TYPE = 'videoSmallCard';

class VideoDetailPage extends StatefulWidget {
  final Data videoData;

  const VideoDetailPage({Key key, this.videoData}) : super(key: key);

  @override
  _VideoDetailState createState() => _VideoDetailState();
}

class _VideoDetailState extends State<VideoDetailPage>
    with WidgetsBindingObserver {
  // 允许element在树周围移动(改变父节点), 而不会丢失状态
  final GlobalKey<VideoPlayState> videoKey = GlobalKey();
  Data data;
  List<Item> itemList = [];
  int _videoId;
  ViewState viewState = ViewState.loading;

  @override
  void initState() {
    data = widget.videoData == null ? arguments() : widget.videoData;
    WidgetsBinding.instance.addObserver(this); //监听页面可见与不可见状态
    loadVideoData();
  }
  @override
  dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _scaffold();
  }

  _scaffold() {
    return Scaffold(
      body: Column(
        children: [
          // AnnotatedRegion：改变状态栏内容的颜色
          AnnotatedRegion(
              child: _statusBar(), value: SystemUiOverlayStyle.light),
          Hero(
              tag: '${data.id}${data.time}',
              child: VideoPlayWidget(
                key: videoKey,
                url: data.playUrl,
              )),
          Expanded(
            flex: 1,
            child: LoadingStateWidget(
              viewState: viewState,
              retry: loadVideoData,
              child: Container(
                decoration: _decoration(), //设置背景色
                // CustomScrollView结合Sliver可以防止滚动冲突
                // 自定义组合滑动
                child: CustomScrollView(
                  slivers: [
                    _sliverToBoxAdapter(),
                    _sliverList()
                  ],
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
//推荐其他视频
  Widget _sliverList(){
    return SliverList(delegate:SliverChildBuilderDelegate((context,index){
      if(itemList!= null&&itemList[index].type == VIDEO_SMALL_CARD_TYPE){
        return VideoItemWidget(data:itemList[index].data,
            callBack:(){
          Navigator.pop(context);
          toPage(VideoDetailPage(videoData: itemList[index].data,));
            }
        );
      }
return Padding(padding: EdgeInsets.all(10),
child: Text(
  itemList[index].data.text,
  style: TextStyle(
    color: Colors.white,
    fontWeight: FontWeight.bold,
    fontSize: 16
  ),
),);
    },
    childCount:itemList.length ));
  }
  /// SliverToBoxAdapter：与CustomScrollView配合使用，包含普通组件（CustomScrollView只能包含sliver系列组件）
  Widget _sliverToBoxAdapter() {
    return SliverToBoxAdapter(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //标题
          _videoTitle(),
          //视频分类及上架时间
          _videoTime(),
          //视频描述
          _videoDescription(),
          //视频状态：点赞转发 评论
          _videoState(),
          Padding(
            padding: EdgeInsets.only(top: 10),
            child: Divider(
              height: 0.5,
              color: Colors.white,
            ),
          ),
          //作者介绍
          _videoAuthor(),
          Divider(
            height: 0.5,
            color: Colors.white,
          )
        ],
      ),
    );
  }

  //标题
  Widget _videoTitle() {
    return Padding(
        padding: EdgeInsets.only(left: 10, top: 10),
        child: Text(
          data.title,
          style: TextStyle(
              fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
        ));
  }

  //视频分类及上架时间
  Widget _videoTime() {
    return Padding(
      padding: EdgeInsets.only(left: 10, top: 10),
      child: Text(
        '#${data.category} / ${formatDateMsByYMDHM(data.author.latestReleaseTime)}',
        style: TextStyle(color: Colors.white, fontSize: 12),
      ),
    );
  }

  //视频描述
  Widget _videoDescription() {
    return Padding(
      padding: EdgeInsets.only(left: 10, top: 10, right: 10),
      child: Text(
        data.description,
        style: TextStyle(color: Colors.white, fontSize: 14),
      ),
    );
  }

  //视频状态：点赞转发 评论
  Widget _videoState() {
    return Padding(
      padding: EdgeInsets.only(left: 10, top: 10),
      child: Row(
        children: [
          _row('images/ic_like.png', '${data.consumption.collectionCount}'),
          Padding(
            padding: EdgeInsets.only(left: 3),
            child: _row(
                'images/ic_share_white.png', '${data.consumption.shareCount}'),
          ),
          Padding(
            padding: EdgeInsets.only(left: 3),
            child: _row(
                'images/icon_comment.png', '${data.consumption.replyCount}'),
          )
        ],
      ),
    );
  }

  Widget _row(String image, String text) {
    return Row(
      children: [
        Image.asset(
          image,
          height: 22,
          width: 22,
        ),
        Padding(
          padding: EdgeInsets.only(left: 3),
          child: Text(
            text,
            style: TextStyle(color: Colors.white, fontSize: 13),
          ),
        )
      ],
    );
  }

  //作者介绍
  Widget _videoAuthor() {
    return Row(
      children: [
        Padding(
          padding: EdgeInsets.all(10),
          child: ClipOval(
            child: cacheImage(data.author.icon, height: 40, width: 40),
          ),
        ),
        Expanded(
          flex: 1,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                data.author.name,
                style: TextStyle(fontSize: 15, color: Colors.white),
              ),
              Padding(
                padding: EdgeInsets.only(top: 3),
                child: Text(
                  data.author.description,
                  style: TextStyle(fontSize: 13, color: Colors.white),
                ),
              ),

            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(right: 10),
          child: Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5)),
            padding: EdgeInsets.all(5),
            child: Text(
              TipUtil.add_follow,
              style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.grey,
                  fontSize: 12),
            ),
          ),
        )
      ],
    );
  }

  //设置背景色
  Decoration _decoration() {
    return BoxDecoration(
      image: DecorationImage(
          //背景图片
          fit: BoxFit.cover,
          image: cachedNetworkImageProvider(
              '${data.cover.blurred}}/thumbnail/${MediaQuery.of(context).size.height}x${MediaQuery.of(context).size.width}')),
    );
  }

  //状态栏
  Widget _statusBar() {
    // 设置状态栏的背景色为黑色
    return Container(
      height: MediaQuery.of(context).padding.top,
      color: Colors.black,
    );
  }

  //获取视频详情
  void loadVideoData() {
    _videoId = data.id;
    HttpManager.getData('${Url.videoRelatedUrl}${data.id}', success: (json) {
      Issue issue = Issue.fromJson(json);
      itemList = issue.itemList;
      setState(() {
        viewState = ViewState.done;
      });
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    //AppLifecycleState当前页面的状态(是否可见)
    if (state == AppLifecycleState.paused) {
      // 页面不可见时,暂停视频
      // videoKey.currentState：树中当前具有此全局密钥的小部件的State对象
      videoKey.currentState.pause();
    } else {
      videoKey.currentState.paly();
    }
  }
}
